<template>
    <div class="main">
      <p  class="main_text">回收网点</p>
        <!-- ############################################## 表单 ############################################## -->
        <div class="cyr-flex">
            <div>
                <el-button type="primary" @click="RucenterDialogVisible = true" v-if="roleList.write">添加转运站</el-button>
            </div>
          <div class="cyr-flex-box">
            <el-table :data="tableData" style="width: 100%; margin-bottom: 1.25rem"  row-key="id"
                :expand-row-keys="[]" :header-cell-style="{ 'background': '#f0f6fe' }" class="mt20"
                :show-overflow-tooltip="true" v-adaptive border>
                <el-table-column label="公司及网点" prop="name" show-overflow-tooltip width="160" />
                <el-table-column label="公司节点" prop="node" show-overflow-tooltip />
                <el-table-column label="网点仓库ID" prop="warehouseId" show-overflow-tooltip />
                <el-table-column label="网点地址" prop="address" show-overflow-tooltip />
                <el-table-column label="联系电话" prop="phone" show-overflow-tooltip />
                <!-- <el-table-column label="经纬度" prop="longitudeAndLatitude" show-overflow-tooltip /> -->
                <el-table-column label="创建时间" width="160" prop="createdAt" show-overflow-tooltip />
                <el-table-column label="更新时间" width="160" prop="updatedAt" show-overflow-tooltip />
                <el-table-column label="是否启动" prop="status">
                    <template #default="props">
                        {{ props.row.status == 0 ? '' : '' }}
                        <el-switch v-model="props.row.status" v-if="props.row.warehouseId && roleList.write"
                            :active-value="0" :inactive-value="1" @change="handleSwitch(props.row)" />
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="props">
                        <el-button size="small" link type="primary" @click="editForm(props.row)"
                            v-if="props.row.warehouseId && roleList.write">编辑</el-button>
                        <el-button size="small" link type="danger" @click="delForm(props.row.id)"
                            v-if="props.row.warehouseId && roleList.write">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- ############################################## 蒙层 ############################################## -->
        <!-- ****************************** 添加转运站 ****************************** -->
        <el-dialog v-model="RucenterDialogVisible" title="添加转运站" width="40%" align-center @close="closeDig">
            <template #header>
                <div class="df aic">
                    <el-icon style="color: #fff;" size="20">
                        <Edit />
                    </el-icon>&nbsp;
                    <p style="color: #fff;">添加转运站</p>
                </div>
            </template>
            <el-form ref="ruleFormRef" :rules="rules" :model="AddData" label-width="8.125rem" label-position="left"
                class="df fdc aic">
                <el-form-item label="网点名称：" prop="name" style="width: 60%;">
                    <el-input v-model="AddData.name" placeholder="网点名称：" />
                </el-form-item>
                <el-form-item label="网点地址：" prop="address" style="width: 60%;">
                    <el-cascader placeholder="选择住址" v-model="AddData.address" :value="options" :options="options"
                        filterable />
                </el-form-item>
                <el-form-item label="详细地址：" prop="Detailaddress" style="width: 60%;">
                    <el-input v-model="AddData.Detailaddress" placeholder="详细地址：" />
                </el-form-item>
                <el-form-item label="联系电话：" prop="phone" style="width: 60%;">
                    <el-input v-model="AddData.phone" placeholder="联系电话：" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="RucenterDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addForm(ruleFormRef)" :loading="loading" v-if="roleList.write">
                        添加
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- ****************************** 编辑网点 ****************************** -->
        <el-dialog v-model="EditcenterDialogVisible" width="40%" align-center @close="closeDig">
            <template #header>
                <div class="df aic">
                    <el-icon style="color: #fff;" size="20">
                        <Edit />
                    </el-icon>&nbsp;
                    <p style="color: #fff;">编辑网点</p>
                </div>
            </template>
            <el-form ref="ruleFormRef" :rules="rules" :model="EditData" label-width="8.125rem" label-position="left"
                class="df fdc aic">
                <el-form-item label="网点名称：" prop="name" style="width: 60%;">
                    <el-input v-model="EditData.name" placeholder="网点名称：" />
                </el-form-item>
                <el-form-item label="网点地址：" style="width: 60%;">
                    <el-cascader :placeholder="EditData.address" v-model="EditData.address" :value="options"
                        :options="options" filterable />
                </el-form-item>
                <el-form-item label="详细地址：" style="width: 60%;">
                    <el-input v-model="EditData.addressD" placeholder="详细地址：" />
                </el-form-item>
                <el-form-item label="联系电话：" prop="phone" style="width: 60%;">
                    <el-input v-model="EditData.phone" placeholder="联系电话：" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="EditcenterDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveEditForm" :loading="loading" v-if="roleList.write"> 保存
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { Edit } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { formatTime } from '../../../filters/index'
import { AutonaviApi } from '@/api/mapApi.js'    //引入封装的高德地图
import { RequestDisassemblyDotGetlistlimit, RequestEmployeeGetFunctionAuthorize, RequestRecycleStatusChange, RequestDisassemblyDotSave, RequestDisassemblyDotDeleteList, RequestDisassemblyDotGetListLimitTreeByCompany } from "@/api/path/index.js"
import { regionData } from 'element-china-area-data'    //获取地区
const tableData = ref<any>([])
const ruleFormRef = ref<any>()
const loading = ref<any>(false)
/*------------------------------------- 按钮权限 -------------------------------------*/
import useAuthorize from "@/hooks/authorize";
let roleList = useAuthorize()
console.log(roleList)
// const authorizeFlag = ref<any>()
// const btnAuthority = () => {
//     // console.log(' useRouter()', useRouter().currentRoute.value.meta.title);
//     RequestEmployeeGetFunctionAuthorize(useRouter().currentRoute.value.meta.title).then((res: any) => {
//         // console.log(res.resultObj);
//         if (res.resultObj == 'W') {
//             authorizeFlag.value = false
//         } else {
//             authorizeFlag.value = true
//         }
//     })
// }
// btnAuthority()
/*------------------------------------- 按钮权限 -------------------------------------*/
let options = regionData
const AddData = ref<any>({
    name: '',
    address: '',
    Detailaddress: '',
    phone: '',
    longitudeAndLatitude: ''
})
const EditData = ref<any>()
const rules = ref<any>({
    name: [
        { required: true, message: '请输入网点名', trigger: 'blur' },
        // { min: 3, max: 5, message: '请确保名称在3到5位', trigger: 'blur' },
    ],
    address: [
        { required: true, message: '请输入地址', trigger: 'blur' },
        // { min: 3, max: 5, message: '请输入3到5位', trigger: 'blur' },
    ],
    Detailaddress: [
        { required: true, message: '请输入详细地址', trigger: 'blur' },
        // { min: 3, max: 5, message: '请输入正确的url', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请输入电话', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: "blur" },
    ],
})
const multipleSelection = ref<any>([])
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
}
const RucenterDialogVisible = ref<any>(false)
const EditcenterDialogVisible = ref<any>(false)
const StopcenterDialogVisible = ref<any>(false)
// const StartcenterDialogVisible = ref<any>(false)
/* 分页器 */
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    getData()
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    getData()
}
/* ************* 获取列表数据 ************* */
const getData = () => {
    regionData.forEach(item => {
        item.value! = item.label
        item.children?.forEach(val => {
            val.value! = val.label
            val.children?.forEach(i => {
                i.value! = i.label
            })
        })
    })
    RequestDisassemblyDotGetListLimitTreeByCompany().then((res: any) => {
        console.log(res.resultObj);
        res.resultObj.forEach((item: any) => {
            item.name = item.companyName
            item.registAt = formatTime(item.registAt)
            item.updatedAt = formatTime(item.updatedAt)
            item.createdAt = item.registAt
            // if (item.children)
        });
        tableData.value = res.resultObj
    })
}
getData()
const companyNode = JSON.parse(localStorage.getItem('roleInfo')!).company   //所属公司节点
/* ************* 添加转运站 ************* */
const addForm = async (formEl: any | undefined) => {
    /* 高德 */
    // loading.value = true
    if (AddData.value.address != '' && AddData.value.Detailaddress != '') {
        let res = await AutonaviApi(AddData.value.address + AddData.value.Detailaddress)
        AddData.value.longitudeAndLatitude = res.data.geocodes[0].location
    }
    if (!formEl) return
    await formEl.validate((valid: any, fields: any) => {
        if (valid) {
            loading.value = true
            console.log('AddData.value', AddData.value);
            RequestDisassemblyDotSave({
                name: AddData.value.name,
                address: AddData.value.address + ',' + AddData.value.Detailaddress,
                phone: AddData.value.phone,
                companyNode: companyNode,
                longitudeAndLatitude: AddData.value.longitudeAndLatitude,
            }).then((res: any) => {
                if (res.code == 0) {
                    ElMessage.success(res.msg)
                    getData()
                    RucenterDialogVisible.value = false
                    loading.value = false
                } else {
                    ElMessage.error(res.msg)
                }
            })
            /* 菜单列表请求接口 */
        } else {
            console.log('error submit!', fields)
        }
    })
}
const closeDig = () => {
    loading.value = false
    AddData.value.name = ''
    AddData.value.address = ''
    AddData.value.Detailaddress = ''
    AddData.value.phone = ''
    AddData.value.longitudeAndLatitude = ''
    getData()
}
const handleSwitch = (row: any) => {
    RequestRecycleStatusChange(row.id).then((res: any) => {
        if (res.code == 0) {
            ElMessage.success(res.msg)
            getData()
        } else {
            ElMessage.error(res.msg)
        }
    })
}

/* ************* 编辑网点 ************* */
const editForm = (row: any) => {
    console.log(row.address.lastIndexOf(','));
    console.log(row.address.substring(row.address.lastIndexOf(',') + 1));
    row.addressD = row.address.substring(row.address.lastIndexOf(',') + 1)
    row.address = row.address.substring(0, row.address.lastIndexOf(','))
    EditData.value = row
    console.log(EditData.value);
    EditcenterDialogVisible.value = true
}
/* ************* 编辑网点--保存 ************* */
const saveEditForm = () => {
    AutonaviApi(EditData.value.address + ',' + EditData.value.addressD).then((res: any) => {
        RequestDisassemblyDotSave({
            id: EditData.value.id,
            name: EditData.value.name,
            address: EditData.value.address + ',' + EditData.value.addressD,
            phone: EditData.value.phone,
            companyNode: companyNode,
            longitudeAndLatitude: res.data.geocodes[0].location,
        }).then((res: any) => {
            if (res.code == 0) {
                ElMessage.success(res.msg)
                getData()
                EditcenterDialogVisible.value = false
            } else {
                ElMessage.error(res.msg)
            }
        })
    })
}
/* ************* 删除网点 ************* */
const delForm = (id: any) => {
    const idsArr = new FormData()
    idsArr.append('ids', id)
    RequestDisassemblyDotDeleteList(idsArr).then((res: any) => {
        if (res.code == 0) {
            ElMessage.success(res.msg)
            getData()
            StopcenterDialogVisible.value = false
        } else {
            ElMessage.error(res.msg)
        }
    })
}
</script>

<style scoped lang="scss">
.main {
    width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
    .top {
        width: 100%;
        background-color: #fff;
    }

    .main_nav {
        background-color: #fff;
    }

    .content {
        width: 100%;
        background-color: #fff;
    }
}


::v-deep .el-form {
    .el-icon svg {
        color: #dcdfe6;
    }
}

::v-deep .el-cascader {
    width: 100% !important;
}
</style>